<template lang="pug">
div
  BottomSheet(
      :isVisible="trayIsVisible"
      @close="trayIsVisible = false"
      )
    Tray(
        :trayList="trayList"
        :trayDropDownList="trayDropDownList"
        @check-input="checkInput"
        )

  FixedScroll
    div(slot="fixed")
      PageHeader(pageTitle="电池收货")
        div(
            v-if="$root.User.permMap['Save(电池收货)']"
            slot="right"
            :class="{'save-disabled': !saveEnabled, active: saveEnabled}"
            @click="save(false)"
            ) 保存

      ScanSearch(
          placeholder="送验单号"
          :initSearchValue="searchValue"
          @search="search"
          @scan="search"
          )

      g-v.info(v-if="info")
        KvPair(v-if="info.EWmNo" k="实体仓库" :v="info.EWmNo")
        KvPair(v-if="info.PullSupplierNum" k="厂家编号" :v="info.PullSupplierNum")

    StatTable.table(
        slot="scroll"
        :headList="headList"
        :body="body"
        :isLoading="isLoading"
        :disabled="!saveEnabled"
        @click-row="clickRow"
        @check-input="checkInput"
        )

    g-h.bottom-bar(slot="fixed-bottom" j-c="flex-end")
      Button(
          @click="trayIsVisible = true"
          text="添加托盘"
          :disabled="trayButton.disabled"
          )

</template>

<script>
import api from "$api"
import util from "$util"
import { mapState } from "vuex"

import Tray from "../order/Tray.vue"

export default {
  components: {
    Tray,
  },
  data() {
    let bodyStyle = {
      color: "#1E88E5",
    }
    return {
      searchValue: "",
      isLoading: false,
      saveEnabled: false,
      hasIllegalInput: false,

      loading: {
        search: false,
        save: false,
      },

      trayIsVisible: false, // 显示托盘按钮
      trayList: [ // 托盘列表
        { code: "", num: 0, title: "" },
      ],
      trayDropDownList: [], // 托盘下拉列表
      trayButton: {
        disabled: true,
      },

      info: null,
      headList: [
        { field: "PartNo", title: "物料号", checked: true, bodyStyle },
        { field: "PartName", title: "物料名称", checked: true },
        { field: "RequiredQty", title: "送验数", checked: true },
        { field: "ActualQty", title: "累计件数", checked: true },
        { field: "Num", title: "接收数", checked: true },
        { field: "WmNo", title: "逻辑仓库", checked: true },
        { field: "PackageModel", title: "器具编号", checked: true },
        { field: "RequiredBoxNum", title: "送验数", checked: true },
        { field: "ActualBoxNum", title: "累计箱数", checked: true },
        { field: "BoxNum", title: "接收数", checked: true, isInput: true },
        { field: "Dloc", title: "库位", checked: true },
      ],
      body: {
        list: [],
      },

      oldNumMap: {}, // 搜索完返回的数量map
    }
  },
  computed: {
    ...mapState({
      barcodeDetail: state => state.battery.barcodeDetail,
    }),
  },
  methods: {
    async search(value) {
      if (this.loading.search) {
        return
      }
      if (value === "") {
        return
      }

      this.loading.search = true
      try {
        let data = await api.BatterySearch({
          ReceiveNo: value,
        })
        this.reset()
        // 清空电池缓存
        this.$store.commit("battery/clearBatteryList")

        for (let item of data.ReceiveDetailInfo) {
          if (item.IsBatch === 0) {
            util.Alert(`物料[${item.PartNo}]的管理模式未维护,请维护库位与物料关系后操作`)
            return
          }
          if (item.IsBatch === 1) {
            util.Alert("该单据需在送验收货界面操作")
            return
          }
        }

        if (data.ReceiveInfo.ConfirmFlag === 2) {
          util.Toast("已完成")
        } else {
          this.saveEnabled = true
          this.trayButton.disabled = false
        }

        let oldNumMap = {}
        for (let item of data.ReceiveDetailInfo) {
          oldNumMap[item.ReceiveDetailId] = item.Num
        }
        this.oldNumMap = oldNumMap

        this.info = data.ReceiveInfo
        this.body.list = data.ReceiveDetailInfo

        // 给下拉列表赋值
        let dropdownList = new Array(data.PackageApplianceInfo.length)
        let i = 0
        for (let item of data.PackageApplianceInfo) {
          dropdownList[i] = {
            name: `${item.PackageNo}(${item.PackageCname})`,
            id: item.PackageNo,
          }
          i++
        }
        this.trayDropDownList = dropdownList

      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.search = false
      }
    },

    async save(IgnoreMaxLimit) {
      if (this.loading.save) {
        return
      }
      if (!this.info || !this.saveEnabled) {
        return
      }
      if (this.hasIllegalInput) {
        util.Alert("输入框中包含不合法的数据")
        return
      }

      for (let item of this.body.list) {
        if (item.Num > item.RequiredQty - item.ActualQty) {
          util.Alert(`物料${item.PartNo}的接收数不能大于剩余需求数量`)
          return
        }
        if (parseInt(item.BoxNum) > item.RequiredBoxNum - item.ActualBoxNum) {
          util.Alert(`物料${item.PartNo}的器具接收数不能大于剩余器具需求数量`)
          return
        }
      }

      // 合并电池码相同的电池的数量
      for (let item of this.body.list) {
        let scanMap = this.barcodeDetail[item.ReceiveDetailId]
        if (scanMap) {
          let lst = new Array(Object.keys(scanMap).length)
          let i = 0
          for (let k in scanMap) {
            lst[i] = scanMap[k]
            i++
          }
          item.barcodeDetailList = lst
        }
      }

      let trayTable = {}
      for (let item of this.trayList) {
        let num = parseInt(item.num)
        if (item.code && num) {
          trayTable[item.code] = num
        }
      }

      this.loading.save = true
      util.Indicator.open()
      try {
        await api.BatterySaveFirst({
          receiveDetailList: this.body.list,
          ReceiveId: this.info.ReceiveId,
          trayTable,
          IgnoreMaxLimit,
        })
        util.Indicator.close()
        util.Toast("保存成功")
        // 清空电池缓存
        this.$store.commit("battery/clearBatteryList")
        await this.search(this.info.ReceiveNo)
      } catch(err) {
        util.Indicator.close()
        this.$root.error(err, true)
        let special = "是否继续保存"
        if (typeof err.msg === "string" && err.msg.indexOf(special) > -1) {
          util.Confirm(err.msg).then((action) => {
            this.save(true)
          }).catch(() => {})
        } else {
          util.Alert(err.msg || "服务器错误")
        }
      } finally {
        this.isLoading = false
        this.loading.save = false
      }
    },

    // 点击行转到扫电池页面
    clickRow(row) {
      this.$router.push({
        path: '/battery/scan',
        query: {
          PartNo: row.PartNo,
          RequiredQty: row.RequiredQty,
          ActualQty: row.ActualQty + row.Num,
          ReceiveNo: this.info.ReceiveNo,
          ReceiveDetailId: row.ReceiveDetailId,
          PullSupplierNum: this.info.PullSupplierNum,
        },
      })
    },

    // 选择下拉列表里的一项
    selectTray(option, i) {
      this.trayList[i].code = option.v
      this.trayList[i].title = option.vTitle
    },
    // 删除下拉列表里的一项
    removeTrayItem(i) {
      this.trayList.splice(i, 1)
    },
    // 添加一条下拉数据
    addTrayItem(i) {
      this.trayList.push({
        title: "",
        num: 0,
      })
    },

    // 重置本页的状态
    reset() {
      this.saveEnabled = false
      this.trayButton.disabled = true
    },

    // 检查输入数据
    checkInput(v, rowIndex, field) {
      let isNatural = /^(0|[1-9]\d*)$/.test(v)
      if (!isNatural) {
        this.hasIllegalInput = true
        util.Alert(`错误的输入: ${v}`)
        return
      }

      if (this.hasIllegalInput) {
        this.hasIllegalInput = false
      }
      if (rowIndex == undefined) {
        return
      }

      let row = this.body.list[rowIndex]
      if (row.Package <= 0) {
        row.Package = 1
      }
      let boxNum = Math.ceil(row.Num / row.Package)
      switch (field) {
        case "Num":
          if (boxNum > row.RequiredBoxNum - row.ActualBoxNum) {
            boxNum = row.RequiredBoxNum - row.ActualBoxNum
          }
          row.BoxNum = boxNum
          if (parseInt(row.Num) > row.RequiredQty - row.ActualQty) {
            util.Alert(`物料${row.PartNo}的接收数不能大于剩余需求数量`)
            this.hasIllegalInput = true
            return
          }
          break
        case "BoxNum":
          if (parseInt(v) > boxNum) {
            util.Alert(`器具接收数需小于本次件数除以收容数(${boxNum})`)
            this.hasIllegalInput = true
            return
          }
          if (parseInt(row.BoxNum) > row.RequiredBoxNum - row.ActualBoxNum) {
            util.Alert(`物料${row.PartNo}的器具接收数不能大于剩余需求数量`)
            this.hasIllegalInput = true
          }
          break
      }
    },

    registerScanner() {
      util.registerScanner((data) => {
        this.searchValue = data
        this.search(data)
      })
    },
  },

  // 切换页面时要重新计算电池数量
  // 电池数量　= 扫描完成时的数量 + 后来扫的电池的数量
  activated() {
    this.registerScanner()

    for (let row of this.body.list) {
      let scanMap = this.barcodeDetail[row.ReceiveDetailId]
      if (scanMap) {
        row.Num = this.oldNumMap[row.ReceiveDetailId] + Object.keys(scanMap).length
      }
    }
  },
  // 离开页面时要清空所有缓存的数据
  beforeDestroy() {
    this.$store.commit("battery/clearBatteryList")
  },
}
</script>

<style lang="stylus" scoped>

.save-disabled
  color: grey500

.active:active
  active-color()

.info
  border: 1px solid grey200

.table
  scan-table()

.bottom-bar
  bottom-bar()

</style>
